package LeetCode.LeetCodeHot;

/**
 * 两数相加
 * @author lumin
 * @date 2022/03/23 13:13
 **/
public class Num2 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode newNode = new ListNode();
        ListNode dummyHead = new ListNode(0,newNode);
        while(l1 != null || l2 != null){
            if(l1 == null && l2 == null){
                break;
            }else {
                ListNode node = new ListNode();
                newNode.next = node;
            }
            if(l1 == null){
                newNode.val =l2.val;
                newNode = newNode.next;
                l2 = l2.next;
            }else if(l2 == null){
                newNode.val =l1.val;
                newNode = newNode.next;
                l1 = l1.next;
            }else{
                newNode.val =l2.val + l1.val;
                newNode = newNode.next;
                l1 = l1.next;
                l2 = l2.next;
            }
        }
        for (ListNode i = dummyHead.next;  i!= null ; i = i.next) {
            if(i.val >= 10){
                i.next.val += 1;
                i.val -= 10;
            }
        }
        for (ListNode i = dummyHead.next;  i!= null ; i = i.next) {
            if(i.next.next == null && i.next.val == 0){
                i.next = null;
                break;
            }
        }
        return dummyHead.next;
    }
}